package pers.cz.util;

import java.sql.*;

/**
 * @program: PostGirl-panent
 * @description: JdbcUtil
 * @author: Cheng Zhi
 * @create: 2022-04-04 16:37
 **/
public class JdbcUtil {

    private static Connection connection;
    private static Statement statement;

    /**
     * 获取statement对象
     * @param driver
     * @param url
     * @param userName
     * @param passWord
     * @return
     */
    public static Statement getSatement(String driver, String url, String userName, String passWord) {

        try {
            // 通过反射获取驱动
            Object o = Class.forName(driver).newInstance();
            // 保证单例
            if (connection == null) {
                connection = DriverManager.getConnection(url, userName, passWord);
            }

            if (statement == null) {
                statement = connection.createStatement();
            }
            return statement;
        } catch (Exception e) {
            System.out.println("连接数据库出错");
        }

        return statement;
    }

    /**
     * 获取Connection对象
     * @param driver
     * @param url
     * @param userName
     * @param passWord
     * @return
     */
    public static Connection  getConnection(String driver, String url, String userName, String passWord) {

        try {
            // 通过反射获取驱动
            Object o = Class.forName(driver).newInstance();
            // 保证单例
            if (connection == null) {
                connection = DriverManager.getConnection(url, userName, passWord);
            }
            return connection;
        } catch (Exception e) {
            System.out.println("连接数据库出错");
        }

        return connection;
    }
    /**
     * 执行sql语句
     * @param sql
     */
    public void execute(String sql) {

        try {
            statement.execute(sql);
        } catch (SQLException e) {
            System.out.println("执行sql出错");
        }
    }

    /**
     * 执行带有返回结果的查询语句
     * @param sql
     * @param flag
     * @return
     */
    public ResultSet execute(String sql, boolean flag) {

        try {
            ResultSet resultSet = statement.executeQuery(sql);
            return resultSet;
        } catch (SQLException e) {
            System.out.println("执行查询语句出错");
        }

        return null;
    }
}
